<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/6/26
 * Time: 14:02
 */

namespace app\common\lib;

use app\common\cachemodel\MapUnlockResult;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\Recode;
use app\common\lib\astrolog\Acg;
use app\common\model\AppLogicVersion;
use app\common\model\AwardGoods;
use app\common\model\FateCity;
use app\common\model\MessageCenter;
use app\common\model\Orders;
use app\common\model\SystemLogicVersion;
use app\common\model\User;
use think\Cache;
use think\Exception;
use think\Log;
use think\queue\Job;

/**
 * 幸运之城队列消费
 * Class AstroMapJob
 * @package app\common\lib
 */
class AstroMapJob
{
    protected $error = '';

    /**
     * 幸运之城队列消费
     * @param Job $job
     * @param $jobData
     */
    public function task1(Job $job, $jobData): void
    {
//        $RecodeInfo = (new Recode())->getRecode(['id' => 553379]);
//        $jobData = [
//            'id' => 1,//订单id或赠送id,用于修改状态
//            'uid' => 10254508,
//            'rid' => 553379,// 档案id
//            'rname' => '测试',// 档案名称
//            'sex' => $RecodeInfo['type'],// 档案性别
//            'isself' => $RecodeInfo['isself'],
//            'longitude' => ($RecodeInfo['long_deg'] + $RecodeInfo['long_min'] / 60) * $RecodeInfo['ew'],// 用户出生地经度
//            'latitude' => ($RecodeInfo['lat_deg'] + $RecodeInfo['lat_min'] / 60) * $RecodeInfo['ns'],// 用户出生地纬度
//            'time' => strtotime($RecodeInfo['year'] . '-' . $RecodeInfo['month'] . '-' . $RecodeInfo['day'] . ' ' . $RecodeInfo['hour'] . ':' . $RecodeInfo['minute'])
//                - ($RecodeInfo['timezone'] + $RecodeInfo['is_summer']) * 3600,// 用户出生时间
//            'data_type' => 1,//1=>订单,2=>赠送
//        ];
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "地图计算 开始:{$startTime} host:{$host} uid:{$jobData['uid']} rid:{$jobData['rid']} name:{$jobData['rname']}";

        try
        {
            $OrdersModel = new Orders();
            $AwardGood = new AwardGoods();
            $AcgLib = new Acg();
            $calculate = true;
            // 一二三级城市配置文件合并统一
            $citys = config('city.city_list');
            $jobData['fate'] = true;
            $score = [];
            if (!empty($citys))
            {
                foreach ($citys as $k => $city)
                {
                    $jobData['point_longitude'] = $city['lon'];
                    $jobData['point_latitude'] = $city['lat'];
                    $score[$k] = $AcgLib->getRecommendedInfo($jobData);
                }
            }

            $list = $fates = [];
            foreach ($score as $i => $c)
            {
                foreach ($c as $j => $s)
                {
                    $list[$j][$i] = $s;
                }
            }

            foreach ($list as $fate => $l)
            {
                $max = max($l);

                if ($max <= 0)
                {
                    continue;
                }
                foreach ($l as $key => $m)
                {
                    // 获取最大值城市 key
                    if ($m == $max)
                    {
                        $lon_lat = $citys[$key];// 命运之城城市经纬度
                        $fates[] = [
                            'id' => $fate,
                            'uid' => $jobData['uid'],
                            'rid' => $jobData['rid'],
                            'longitude' => $lon_lat['lon'],
                            'latitude' => $lon_lat['lat']
                        ];
                    }
                }
            }

            try
            {
                (new FateCity())->saveFateCity($fates);// 保存命运之城入库
                $this->mapUnlockResultCul($jobData);//添加结果数据
                // 将计算数据存入缓存
                Cache::rm(FateCity::$cacheKey . $jobData['rid']);

                $SystemLogicModel = new SystemLogicVersion();
                $logicVersionData = [
                    'rid' => $jobData['rid'],
                    'type' => 1,
                ];
                // 获取当前最新的逻辑版本号
                $logic_lastes = $SystemLogicModel->getVersion(['type' => $logicVersionData['type']]);
                $logicVersionData['version'] = $logic_lastes['version'] ?? 0;
                // 获取当前档案逻辑版本号
                $AppLogicModel = new AppLogicVersion();
                $logic_user = $AppLogicModel->getVersion([
                    'rid' => $jobData['rid'],
                    'type' => $logicVersionData['type'],
                ]);
                // 新增
                if (!$logic_user)
                {
                    $AppLogicModel->addVersion($logicVersionData);
                } // 更新了逻辑
                elseif ($logicVersionData['version'] && $logic_user < $logicVersionData['version'])
                {
                    $AppLogicModel->updateVersion($logicVersionData);
                }
                // 将幸运之城按钮更新状态改为无需更新
                Cache::rm($jobData['uid'] . ':' . $jobData['rid'] . '_acg_logic_status');
            }
            catch (\Exception $e)
            {
                $calculate = false;
                $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
            }


            if ($calculate === true)
            {
                // 更新订单状态为，计算完成
                if ($jobData['data_type'] == 1)
                {
                    try
                    {
                        // 更新2.0订单缓存
                        (new OrdersCacheModel())->UpdateData($jobData['order_id'], ['status' => 4], 4);
                        // 删除订单详情
                        Cache::rm(Orders::ORDER_INFO_ID . $jobData['id']);
                        // 删除订单缓存
                        $OrdersModel->rm_cache(['oid' => $jobData['id'], 'del_add' => 0, 'uid' => $jobData['uid']]);
                        // 删除幸运之城赠送缓存
                        Cache::rm('recode_lines_' . $jobData['rid']);
                    }
                    catch (\Exception $e)
                    {
                        $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
                    }
                } else
                {
                    // 后台赠送时,修改状态
                    try
                    {
                        $AwardGood->where('id', $jobData['id'])->update(['status' => 1]);

                        // 删除幸运之城赠送缓存
                        Cache::rm('recode_lines_' . $jobData['rid']);
                    }
                    catch (\Exception $e)
                    {
                        $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
                    }
                }
                //获取用户信息
                $userinfo = (new User())->getUserinfo(['id' => $jobData['uid']]);

                //若推送开关开启则发起推送和消息
                if (isset($jobData['push_switch']) && $jobData['push_switch'])
                {
                    $recodeStatus = (new Recode())->getInfoById($jobData['rid'], ['status']);
                    $link = $recodeStatus['status']
                        ? 'acg_map?rid=' . $jobData['rid'] . '&need_auth=1'
                        : "acg_map_history?need_auth=2&order_id={$jobData['order_id']}&rid={$jobData['rid']}";
                    // PUSH推送
                    $pushRes = (new Push())->pushUserMsg($jobData['uid'], '您购买的' . $jobData['rname'] . '的幸运之城已经计算完成了，点击查看详情！', ['target' => 'local', 'link' => $link, 'action' => 'extend']);
                    if (!$pushRes['success'])
                    {
                        $logInfo .= ' error: 计算完成,推送失败 message:' . $pushRes['message'];
                    }

                    // 消息中心添加信息
                    $messageData = [
                        'status' => 0,
                        'is_read' => 0,
                        'range' => $userinfo['id'],
                        'type' => 2,
                        'reid' => 0,
                        'cid' => 4,// 幸运之城
                        'title' => '幸运之城计算完成',
                        'content' => '您购买的' . $jobData['rname'] . '的幸运之城已经计算完成了，点击查看详情！',
                        'link' => $link,
                        'target' => 'local',
                        'create_time' => time()
                    ];
                    try
                    {
                        (new MessageCenter())->pushMessage($userinfo['id'], $messageData);
                    }
                    catch (\Exception $e)
                    {
                        $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
                    }
                }

                $logInfo .= ' success:' . date('Y-m-d H:i:s');

                $job->delete();
            } else
            {
                // 删除幸运之城赠送缓存
                Cache::rm('recode_lines_' . $jobData['rid']);
                // 更新幸运之城赠送状态为队列失败
                $logInfo .= ' failed:' . date('Y-m-d H:i:s');
            }
        }
        catch (Exception $e)
        {
            $logInfo .= ' error:' . $e->getMessage() . ' file:' . $e->getFile() . ':' . $e->getLine();
        }

        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }

    /**
     * 处理地图结果数据
     * @param $jobData
     * @throws \Exception
     */
    protected function mapUnlockResultCul($jobData)
    {
        if ($jobData['data_type'] == 1)
        {
            $ids = (new MapUnlockResult())->getUnlockIdsFromCache(1, $jobData['order_id']);
        } else
        {
            $ids = (new MapUnlockResult())->getUnlockIdsFromCache(2, $jobData['id']);
        }
        if ($ids)
        {
            //更新数据
            (new MapUnlockResult())->updateData($ids, ['status' => 2]);
        }
    }
}
